package br.ufc.si.sd.skaletor;


import br.ufc.si.sd.servidor.Servidor;
import com.google.protobuf.ByteString;
import java.net.*;
import java.io.*;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import protos.br.ufc.si.sd.gerado.Message.RequestMessage;

public class Gerenciador extends Thread {

    private DataInputStream in;
    private DataOutputStream out;
    private Servidor servidor;

    public Gerenciador(Socket cliente, Servidor servidor) {
        try {
            this.in = new DataInputStream(cliente.getInputStream());
            this.out= new DataOutputStream(cliente.getOutputStream());
            this.servidor = servidor;
        } catch (IOException ex) {
            Logger.getLogger(Gerenciador.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void run() {


        try {

            while(in.available()==0){};
            byte[] data = new byte[in.available()];
            in.read(data);
            System.out.println("Recebi");
            RequestMessage request = RequestMessage.parseFrom(data);
            System.out.println("Bytes recebidos: " + request.getArgs());
            System.out.println("Nome do Método a ser executado: " + request.getMetodo());

                try {
                    Class c = this.servidor.getClass();
                    Class[] params = {ByteString.class};
                    Method m = c.getMethod(request.getMetodo(), params);
                    byte[] response = (byte[])m.invoke(servidor, request.getArgs());
                    out.write(response);
               
                } catch (Exception e) {
                    System.out.println("Deu pau :" + e.getMessage());
                    e.printStackTrace();

                }
           
        } catch (EOFException e) {
            System.out.println("EOF:" + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO:" + e.getMessage());
        } 

    }
}

